package com.hunttown.mes.common.utils;

import java.math.BigDecimal;

/**
 * created by wangjunfu on 2020-07-26
 */
public class MoneyToChineseUtils {

    //金额转换成汉字大写金额
    public static String digitCapital(double money) {
        String fraction[] = {"角", "分"};
        String digit[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
        String unit[][] = {{"元", "万", "亿"}, {"", "拾", "佰", "仟"}};

        String head = money < 0 ? "负" : "";
        // 如果是负数取绝对值
        money = Math.abs(money);
        String s = "";
        BigDecimal bigDecimal = new BigDecimal(Double.valueOf(money).toString());
        String nStr = bigDecimal.toString();
        // 小数部分
        String[] split = nStr.split("\\.");
        if (split.length > 1) {
            // 小数点为特殊符号，在分割时需进行转义
            String decimalStr = split[1];
            if (decimalStr.length() > 2) {
                decimalStr = decimalStr.substring(0, 2);
            }
            // 将小数部分转换为整数
            Integer integer = Integer.valueOf(decimalStr);
            String p = "";
            for (int i = 0; i < decimalStr.length() && i < fraction.length; i++) {
                p = digit[integer % 10] + fraction[decimalStr.length() - i - 1] + p;
                integer = integer / 10;
            }
            s = p.replaceAll("(零.)+", "") + s;
        }
        if (s.length() < 1) {
            s = "整";
        }
        int integerPart = (int) Math.floor(money);
        // 整数部分
        for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
            String p = "";
            for (int j = 0; j < unit[1].length && money > 0; j++) {
                p = digit[integerPart % 10] + unit[1][j] + p;
                integerPart = integerPart / 10;
            }
            s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;
        }
        return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
    }

    public static void main(String[] args) throws Exception {
        System.out.println(digitCapital(2536));
        System.out.println(digitCapital(25.36));
        System.out.println(digitCapital(-25.36));
        System.out.println(digitCapital(25.3693));
        System.out.println(digitCapital(245664625.36));
    }
}
